﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kooboo.CMS.CustomSettingSyncWrapper
{
    public class CustomResponseFilter : MemoryStream
    {
        private readonly Stream _response;
        public CustomResponseFilter(Stream response)
        {
            _response = response;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            var html = Encoding.UTF8.GetString(buffer);
            html = AppendJavascript(html);
            buffer = Encoding.UTF8.GetBytes(html);
            _response.Write(buffer, offset, buffer.Length);
        }

        private string AppendJavascript(string html)
        {
            if (html.Trim().EndsWith("</html>", StringComparison.InvariantCultureIgnoreCase))
            {
                html += "<script type=\"text/javascript\" src=\"/Kooboo_CMS_CustomSettingSyncWrapper/Resource/Script\"></script>";
            }

            return html;
        }
    }
}
